package com.practice.blog.common.utils;

import com.practice.blog.common.exception.BlogException;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import java.nio.charset.StandardCharsets;
import java.util.UUID;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: hp
 * Date: 2025-02-01
 * Time: 14:33
 */
public class SecurityUtil {
    //加密
    public static String encrypt(String password) {
        if(!StringUtils.hasLength(password)) {
            throw new BlogException("用户未输入密码！");
        }
        //生成盐值
        String sale = UUID.randomUUID().toString().replace("-","");
        //生成密文
        String securityPassword = DigestUtils.md5DigestAsHex((sale + password).getBytes(StandardCharsets.UTF_8));
        return sale + securityPassword;
    }

    //验证
    public static Boolean verify(String inputPassword,String sqlPassword) {
        if(!StringUtils.hasLength(inputPassword) || !StringUtils.hasLength(sqlPassword) || sqlPassword.length() != 64 ) {
            return false;
        }
        //获取SQL中的盐值
        String sale = sqlPassword.substring(0,32);
        //用户输入的明文和盐值进行MD5
        String securityPssword = DigestUtils.md5DigestAsHex((sale+inputPassword).getBytes(StandardCharsets.UTF_8));
        return sqlPassword.equals(sale + securityPssword);
    }
}
